import React, { Component } from 'react'
import { View, Text, Navigator } from '@tarojs/components'
import { AtButton, AtForm, AtInput, AtToast } from 'taro-ui'
import Taro from "@tarojs/taro"

import { login } from "../../api";
import { UserId } from "../../util";
import './index.scss'

type LoginState = {
  phone: string,
  password: string
}
interface Toast {
  toastText: string,
  toastIcon?: string,
  toastIsOpen: boolean,
  toastState: 'success' | 'error' | 'loading'
}

export default class Index extends Component<any, LoginState & Toast> {

  constructor(args) {
    super(args);
    this.state = {
      phone: '',
      password: '',
      toastIsOpen: false,
      toastState: 'success',
      toastText: ''
    }
  }

  handleSubmit = (e) => {
    login(this.state).then((res: any) => {
      if (res.state === 0) {
        UserId.set(res.data.id)
        this.setState({
          toastState: 'success',
          toastIsOpen: true,
          toastText: '登录成功'
        })
        setTimeout(() => {
          this.setState({
            toastIsOpen: false
          })
        }, 1500)
        Taro.switchTab({
          url: '/pages/index/index'
        })
      }
    }, rej => {
      this.setState({
        toastState: 'error',
        toastIsOpen: true,
        toastText: rej.msg
      })
      setTimeout(() => {
        this.setState({
          toastIsOpen: false
        })
      }, 1500)
    })
  }
  handleUserChange = (value) => {
    this.setState({
      phone: value
    })
    return value;
  }
  handlePasswordChange = (value) => {
    this.setState({
      password: value
    })
    return value;
  }
  render() {
    return (
      <View className='wrapper'>
        <AtToast isOpened={this.state.toastIsOpen} status={this.state.toastState} text={this.state.toastText}></AtToast>
        <Text className='title'>羊羊快递·登录</Text>
        <AtForm onSubmit={this.handleSubmit}>
          <AtInput title="账号" name="user" onChange={this.handleUserChange} value={this.state.phone} placeholder='请输入注册的手机号' type='phone'></AtInput>
          <AtInput title="密码" name="password" onChange={this.handlePasswordChange} value={this.state.password} placeholder='请输入密码' type='password'></AtInput>
          <AtButton onClick={this.handleSubmit}>登录</AtButton>
        </AtForm>
        <Navigator style='float:right;display:block;padding:20px' className='info-primary' url='/pages/register/index'>没有账号，注册一个？</Navigator>
      </View>
    )
  }
}
